<?php
declare (strict_types=1);

namespace app\api\controller;
use app\model\UserModel;
use app\model\LikeModel;
use app\model\CommentModel;
use app\model\ArticleModel;
use app\model\CollectModel;
use app\model\ShareModel;
use think\facade\Request;
use think\facade\Validate;


class Article
{
    // 文章列表
    public function list()
    {
        $params = Request::param();
        $params['category_id'] = $params['category_id'] ?? 0;
        $params['page'] = $params['page'] ?? 1;
        $params['page_size'] = $params['page_size'] ?? 30;
        $validate = Validate::rule([
            'page' => 'between:1,' . PHP_INT_MAX,
            'page_size' => 'between:1,' . PHP_INT_MAX,
        ]);
        if (!$validate->check($params)) {
            echo $validate->getError();
            exit();
        }

//        $articleList = ArticleModel::where('category_id', '=', 1)
//            ->order('add_time desc')
//            ->paginate(['list_rows' => 10]);
//        var_dump($articleList);exit();

        $model = ArticleModel::where('article_id', '>', 0);
        if ($params['category_id']) {
            $model->where('category_id','=', $params['category_id']);
        }
        $result = $model->order('add_time desc')
            ->paginate(['list_rows' => $params['page_size'], 'page' => $params['page']]);

        $articleList = [];
        $likeList=[];
        $commentList=[];
        
      
        foreach ($result as $item) {
        // var_dump($item['article_id']);
        $articleIds = $item['article_id'];//获取文章id
        //从数据库按时间降序获取相关数据
        $likeResult = LikeModel::where("article_id", "=", $articleIds)->order('add_time', 'desc')->count();
        $likeList[]=$likeResult;
        
        $commentResult = CommentModel::where("article_id", "=", $articleIds)->where("status","=",1)->order('add_time', 'desc')->count();
        $commentList[]=$commentResult;
        
        $articleList[] = $item;
            
        }
        
        $data = [
            'status' => 0,
            'message' => '',
            'data' => [
                'articleList' => $articleList,
                'likeList' => $likeList,
                'commentList' => $commentList,
                'total' => $result->total()
            ],
        ];
        return json($data);
    }
    
    
    
    // 文章详情接口
    public function detail()
    {
        $articleId = Request::param("article_id");
        $validate = Validate::rule([
            'article_id|文章id' => 'require|between:1,' . PHP_INT_MAX,
        ]);
        if (!$validate->check(['article_id' => $articleId])) {
            $data = [
                'status' => 10001,
                'message' => $validate->getError(),
                'data' => [],
            ];
            return json($data);
        }

        $article = ArticleModel::find($articleId);
        if (!$article) {
            $data = [
                'status' => 11001,
                'message' => '文章不存在',
                'data' => [],
            ];
            return json($data);
        }

        $data = [
            'status' => 0,
            'message' => '',
            'data' => [
                'article' => $article,
            ],
        ];
        return json($data);
    }


    //点赞增加
     public function like()
    {
        $param = Request::param();
        $userName=Request::param('user_name');
        
        $validate = Validate::rule([
            // 'user_id' => 'require|between:1,' . PHP_INT_MAX,
            'user_name' => 'require|min:1|max:20',
            'article_id' => 'require|between:1,' . PHP_INT_MAX,
        ]);

        if (!$validate->check($param)) {
            $date = [
                'status' => 10002,
                'message' => $validate->getError(),
                'date' => []
            ];
            return json($date);
        }
        

        $insertData = $param;
        $insertData['add_time'] = $insertData['update_time'] = time();
        
        $userId = UserModel::where("user_name","=",$userName)->value("user_id");
        $insertData['user_id']=$userId;

        
        $result=LikeModel::create($insertData);
        $data = [
                'status' => 0,
                'message' => '',
                'data' => [
                    'result' => true,
                    'list' => $result->toArray()
                    ]
                ];
        return json($data);
    }


    //点赞列表
    public function likelist()
    {
        //接收article_id参数
        //根据article_id获取相关点赞列表
        $articleId = Request::param("article_id");
        $validate = Validate::rule([
            'article_id' => 'require|between:1,' . PHP_INT_MAX,
        ]);
        if (!$validate->check(['article_id' => $articleId])) {
            $date = [
                'status' => 10002,
                'message' => $validate->getError(),
                'date' => []
            ];
            return json($date);
        }

        //根据文章id从数据库获取相关数据（按时间降序）
        $result = LikeModel::where("article_id", "=", $articleId)->order('add_time', 'desc')->select();

        $likeList = [];
        foreach ($result as $row) {
            $temp = $row->toArray();

            $likeList[] = [
                'like_id' => $temp['like_id'],
                'user_id' => $temp['user_id'],
                'user_name' => $temp['user_name'],
                'article_id' => $temp['article_id'],
                'add_time' => $temp['add_time'],
            ];
        }
        $data = [
            'status' => 0,
            'message' => '',
            'data' => [
                'likeList' => $likeList
            ]
        ];
        return json($data);
    }

    //点赞删除
     public function likedelete()
    {
        //接收article_id参数
        //根据article_id获取相关点赞列表
        $param = Request::param();
        $articleId=$param['article_id'];
        $userName=$param['user_name'];
        

        $validate = Validate::rule([
            'user_name' => 'require|min:1|max:20',
            'article_id' => 'require|between:1,' . PHP_INT_MAX,
        ]);
        if (!$validate->check(['article_id' => $articleId],['user_name'=>$userName])) {
            echo $validate->getError();
            exit();
        }
        
        $userId = UserModel::where("user_name","=",$userName)->value("user_id");

        $param['user_id']=$userId;

        //从数据库删除相关数据
        $result = LikeModel::destroy($param);

        $data = [
                'status' => 0,
                'message' => '',
                'data' => [
                    'result' => true,
                    'list' => $result
                    ]
                ];
        return json($data);
    }
   
     //收藏增加
    public function collect()
    {
        $param = Request::param();
        $userName=Request::param('user_name');
        
        $validate = Validate::rule([
            // 'user_id' => 'require|between:1,' . PHP_INT_MAX,
            'user_name' => 'require|min:1|max:20',
            'article_id' => 'require|between:1,' . PHP_INT_MAX,
        ]);

        if (!$validate->check($param)) {
            $data = [
                'status' => 10002,
                'message' => $validate->getError(),
                'data' => []
            ];
            return json($data);
        }
        

        $insertData = $param;
        $insertData['add_time'] = $insertData['update_time'] = time();
        
        $userId = UserModel::where("user_name","=",$userName)->value("user_id");
        $insertData['user_id']=$userId;

        
        $result=CollectModel::create($insertData);
        $data = [
                'status' => 0,
                'message' => '',
                'data' => [
                    'result' => true,
                    'list' => $result->toArray()
                    ]
                ];
        return json($data);
    }
    
    
      //收藏列表011
     public function collectLists()
    {
        $param = Request::param();
        $userName=Request::param('user_name');
        
        $validate = Validate::rule([
            'user_name' => 'require|min:1|max:20',
        ]);

        if (!$validate->check($param)) {
            $data = [
                'status' => 10002,
                'message' => $validate->getError(),
                'data' => []
            ];
            return json($data);
        }
        
        
        //查询收藏记录
        $collectLists = CollectModel::where("user_name","=",$userName)->select();
        //根据查询到的收藏记录，获取文章id的数组
        $articleId=[];
        foreach ($collectLists as $item){
            $articleId[]=$item['article_id'];
        }
        
        
        //根据文章id获取对应文章信息
        $articleList=[];
        $commentList=[];
        $likeList=[];
        foreach ($articleId as $item){
            $articleList[]=ArticleModel::where("article_id","=",$item)->find();

            $likeResult = LikeModel::where("article_id", "=", $item)->order('add_time', 'desc')->count();
            $likeList[]=$likeResult;
        
            $commentResult = CommentModel::where("article_id", "=", $item)->where("status","=",1)->order('add_time', 'desc')->count();
            $commentList[]=$commentResult;
            
        }

        $data = [
            'status' => 0,
            'message' => '',
            'data' => [
                '1' => 1,
                'articleId' => $articleId,
                'collectLists' => $collectLists,
                'articleList' => $articleList,
                'commentList' => $commentList,
                'likeList' => $likeList,
            ],
        ];
        return json($data);
    }

    
    
     //收藏列表022
    public function collectlist()
    {
        //接收article_id参数
        //根据article_id获取相关评论列表
        $articleId = Request::param("article_id");
        $validate = Validate::rule([
            'article_id' => 'require|between:1,' . PHP_INT_MAX,
        ]);
        if (!$validate->check(['article_id' => $articleId])) {
            $data = [
                'status' => 10002,
                'message' => $validate->getError(),
                'data' => []
            ];
            return json($data);
        }

       //从数据库按时间降序获取相关数据
        $result = CollectModel::where("article_id", "=", $articleId)->order('add_time', 'desc')->select();

        $collectList = [];
        foreach ($result as $row) {
            $temp = $row->toArray();
            $collectList[] = [
                'collect_id' => $temp['collect_id'],
                'user_id' => $temp['user_id'],
                'user_name' => $temp['user_name'],
                'article_id' => $temp['article_id'],
                'add_time' => $temp['add_time'],

            ];
        }

        $data = [
            'status' => 0,
            'message' => '',
            'data' => [
                'collectList' => $collectList
            ]
        ];
        return json($data);

    }
    
    
     //收藏删除
     public function collectdelete()
    {
        //接收article_id参数
        //根据article_id获取相关收藏列表
        $param = Request::param();
        $articleId=$param['article_id'];
        $userName=$param['user_name'];
        

        $validate = Validate::rule([
            'user_name' => 'require|min:1|max:20',
            'article_id' => 'require|between:1,' . PHP_INT_MAX,
        ]);
        if (!$validate->check(['article_id' => $articleId],['user_name'=>$userName])) {
            echo $validate->getError();
            exit();
        }
        
        $userId = UserModel::where("user_name","=",$userName)->value("user_id");
        $param['user_id']=$userId;

        //从数据库删除相关数据
        $result = CollectModel::destroy($param);

        $data = [
                'status' => 0,
                'message' => '',
                'data' => [
                    'result' => true,
                    'list' => $result
                    ]
                ];
        return json($data);
    }
    

     //分享增加
     public function share()
    {
        $param = Request::param();
        // $articleId=Request::param('article_id');
        
        $validate = Validate::rule([
            // 'user_id' => 'require|between:1,' . PHP_INT_MAX,
            // 'user_name' => 'require|min:1|max:20',
            'article_id' => 'require|between:1,' . PHP_INT_MAX,
        ]);

        if (!$validate->check($param)) {
            $data = [
                'status' => 10002,
                'message' => $validate->getError(),
                'data' => []
            ];
            return json($data);
        }
        

        $insertData = $param;
        $insertData['add_time'] = $insertData['update_time'] = time();
        
        // $userId = UserModel::where("article_id","=",$articleId)->value("user_id");
        // $insertData['user_id']=$userId;

        
        $result=ShareModel::create($insertData);
        $data = [
                'status' => 0,
                'message' => '',
                'data' => [
                    'result' => true,
                    'share' => $result->toArray()
                    ]
                ];
        return json($data);
    }
    
   //分享列表022
    public function sharelist()
    {
        //接收article_id参数
        //根据article_id获取相关评论列表
        $articleId = Request::param("article_id");
        $validate = Validate::rule([
            'article_id' => 'require|between:1,' . PHP_INT_MAX,
        ]);
        if (!$validate->check(['article_id' => $articleId])) {
            $data = [
                'status' => 10002,
                'message' => $validate->getError(),
                'data' => []
            ];
            return json($data);
        }

        //从数据库按时间降序获取相关数据
        $result = ShareModel::where("article_id", "=", $articleId)->order('add_time', 'desc')->select();

        $sharetList = [];
        foreach ($result as $row) {
            $temp = $row->toArray();

            $sharetList[] = [
                'article_id' => $temp['article_id'],
                'add_time' => $temp['add_time'],
            ];
        }

        $data = [
            'status' => 0,
            'message' => '',
            'data' => [
                'sharetList' => $sharetList
            ]
        ];
        return json($data);

    }
}
